package controllers

import (
	"acs/management/models"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/labstack/echo"
)

//添加、 修改
func AddPatchHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	requestbody, requesterr := ioutil.ReadAll(c.Request().Body)
	models.CheckError(requesterr)
	type receiveData struct {
		models.TPatch
		Step int64 `json:"step"`
		Page int64 `json:"page"`
	}

	var currentData receiveData
	err = json.Unmarshal(requestbody, &currentData)
	models.CheckError(err)
	currentData.Createtime = time.Now()
	currentUser := models.CheckLogin(c)
	_, err = models.CheckUserPrivilege(&currentUser, models.TableApp, int(currentData.TAppId), models.RoleUpdate)
	models.CheckError(err)
	currentData.Sn = strings.Trim(currentData.Sn, " ")
	currentData.PreSn = strings.Trim(currentData.PreSn, " ")
	if currentData.Sn == "" || currentData.PreSn == "" {
		models.CheckError(errors.New("空格非法"))
	}
	if currentData.Id > 0 {
		_, err = models.UpdateTPatchById(&currentData.TPatch)
		models.CheckError(err)
		models.AppendLog(&currentUser, "成功修改补丁:"+currentData.Sn, models.LOG_TYPE_PATCH)
	} else {
		currentData.Id, err = models.AddTPatch(&currentData.TPatch)
		models.CheckError(err)
		models.AppendLog(&currentUser, "成功添加补丁:"+currentData.Sn, models.LOG_TYPE_PATCH)
	}
	allStr := c.Param("all")
	var all = 1
	if allStr != "" {
		all, err = strconv.Atoi(allStr)
		models.CheckError(err)
	}
	totalCount, datalist, listErr := models.GetTPatchOfAPP(int64(currentData.TAppId), all, 0, 10)
	models.CheckError(listErr)
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, datalist, totalCount))
	return
}

//注销
func KillPatchHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	operationIDStr := c.Param("id")
	operationID, swtichErr := strconv.Atoi(operationIDStr)
	models.CheckError(swtichErr)
	enableStr := c.Param("enable")
	enable, enableErr := strconv.Atoi(enableStr)
	models.CheckError(enableErr)
	currentUser := models.CheckLogin(c)
	operationItem, getErr := models.GetTPatchById(int64(operationID))
	models.CheckError(getErr)
	// 对app补丁的删除 相当于对app 的修改。
	_, err = models.CheckUserPrivilege(&currentUser, models.TableApp, operationItem.TAppId, models.RoleUpdate)
	models.CheckError(err)
	err = models.KillTPatch(int64(operationID), enable)
	models.CheckError(err)
	if enable == 0 {
		models.AppendLog(&currentUser, "成功注销补丁:"+operationItem.Sn, models.LOG_TYPE_PATCH)
	} else {
		models.AppendLog(&currentUser, "成功启用补丁:"+operationItem.Sn, models.LOG_TYPE_PATCH)
	}

	query := make(map[string]interface{})
	query["t_app_id"] = strconv.Itoa(operationItem.TAppId)
	datalist, _, listErr := models.GetAllTPatch(query, nil, nil, nil, 0, 10000, false)
	models.CheckError(listErr)
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, datalist, -1))
	return
}

//获取列表
func ListPatchByAppHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	operationIDStr := c.Param("appid")
	operationID, swtichErr := strconv.Atoi(operationIDStr)
	models.CheckError(swtichErr)
	currentPageStr := c.Param("page")
	currentPage, switchErr := strconv.Atoi(currentPageStr)
	models.CheckError(switchErr)

	currentStepStr := c.Param("step")
	currentStep, switchErr2 := strconv.Atoi(currentStepStr)
	models.CheckError(switchErr2)
	if currentPage < 1 || currentStep < 1 {
		panic(errors.New("参数不符合标准。"))
	}
	allStr := c.Param("all")
	all, allStrErr := strconv.Atoi(allStr)
	models.CheckError(allStrErr)
	var currentUser *models.UserWithPirvilege
	//普通的请求是需要验证登录的。除非之前明确设置过不需要登录
	if c.Get("needCheckLogin") != false {
		temp := models.CheckLogin(c)
		currentUser = &temp
		_, err = models.CheckUserPrivilege(currentUser, models.TableApp, operationID, models.RoleRead)
		models.CheckError(err)
	}
	totalCount, datalist, listErr := models.GetTPatchOfAPP(int64(operationID), all, (currentPage-1)*currentStep, currentStep)
	models.CheckError(listErr)
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, datalist, totalCount))
	return
}

//获取列表
func GetPatchSpeedByAppHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)

	models.CheckLogin(c)

	datalist, listErr := models.GetPatchCountOfAPP()
	models.CheckError(listErr)
	maxCount := 0
	for i := 0; i < len(datalist); i++ {
		if datalist[i].PatchCount > maxCount {
			maxCount = datalist[i].PatchCount
		}
	}

	result := make(map[string]interface{})
	result["datalist"] = datalist
	result["maxcount"] = maxCount
	c.JSON(http.StatusOK, result)
	return
}
